<?php

namespace app\jobs;
use think\queue\Job;
use think\facade\Log;
class sendJob
{
    // 消费者执行入口
    public function fire(Job $job, $data)
    {
        if(!isset($data['logic']) || !isset($data['method'])){
           $job->delete();   
        }
        // 具体执行业务
        $isJobDone = $this->doJob($data);
        if ($isJobDone) {
            // 消息队列执行成功，删除队列，否则会一直执行
            $job->delete();
        } else {
            // 消息队列执行失败
            $attempts = $job->attempts();
            if($attempts > 3){
                Log::record("任务执行三次仍失败:".json_encode($data));
                $job->delete();
            }

        }
    }

    // 消息队列执行失败后会自动执行该方法
    public function failed($data)
    {
        Log::error('消息队列达到最大重复执行次数后失败：' . json_encode($data));
    }

    // 消息队列执行方法
    public function doJob($data)
    {
        // 具体执行业务
        // $data = json_encode($data);
        if (isset($data['method']) && isset($data['logic'])) {
            $className = '\\app\\api\\Logic\\' . ucfirst(strtolower($data['logic']));

            if (class_exists($className)) {
                $Logic = new $className();

                if (method_exists($Logic, $data['method'])) {
                    $re = call_user_func_array(array($Logic, $data['method']), []);
                    if($re['code'] == 200){
                           echo 'SUCCESS';
                           Log::record("Quene success:".json_encode($data));
                           return true;
                    }else{
                         return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            echo "未知参数";
            return false;
        }
        
    }
}
